package app.controllers;

import app.Const;
import app.models.member.Points;
import app.models.product.Issuer;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import goja.StringPool;
import goja.mvc.Controller;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 积分规则设置
 * </p>
 *
 * @author liuhui
 * @version 1.0
 * @since JDK 1.6
 */
public class PointsController extends Controller {

    /**
     * The index route.
     */
    @Before(GET.class)
    public void index() {
        List<Points> pointsList =  Points.dao.findAvailableAll();
        Map<String, Points> codeMap = Maps.uniqueIndex(pointsList, new Function<Points, String>() {
            @Override
            public String apply(Points points) {
                return points.getStr(Const.FIELD_CODE);
            }
        });
        setAttr("code_map",codeMap);
    }

    @Before(GET.class)
    public void create() {
        Issuer issuer = new Issuer();
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        setAttr(issuer);
        render("item.ftl");
    }

    @Before(GET.class)
    public void edit() {
        String id = getPara(0, "0");
        Issuer issuer = Issuer.dao.findById(id);
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        setAttr("issuer", issuer);
        render("item.ftl");
    }

    @Before(POST.class)
    public void save() {
        Points points = getModel(Points.class);
        if (!Strings.isNullOrEmpty(getPara("points.status"))) {
            points.set(Const.FIELD_STATUS, "1");
        }else {
            points.set(Const.FIELD_STATUS, "0");
        }

        boolean rs;
        if (Strings.isNullOrEmpty(points.getStr(StringPool.PK_COLUMN))) {
            rs = points.save();
        } else {
            rs = points.update();
        }

        if(rs){
            renderAjaxSuccess();
        }else {
            renderAjaxFailure();
        }
    }

    /**
     * 设置启用
     */
    public void setEnable(){
        String code = getPara(0, "0");
        boolean rs = Points.dao.setEnableByCode(code);
        if(rs){
            renderAjaxSuccess("设置成功");
        }else {
            renderAjaxFailure("设置出错了");
        }
    }

    /**
     * 设置禁用
     */
    public void setDisable(){
        String code = getPara(0, "0");
        boolean rs = Points.dao.setDisableByCode(code);
        if(rs){
            renderAjaxSuccess("设置成功");
        }else {
            renderAjaxFailure("设置出错了");
        }
    }
}
